package com.sh.data.engine.domain.dataasset.service;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.sh.data.engine.repository.dao.dataasset.entity.TblPropEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: mengzheng.mhc
 * @date: 2024/6/19 12:25
 */
@Service
@Slf4j
public class TblService {

    @Autowired
    private TblPropService tblPropService;

    public Map<String, Integer> getTableCount(Long projectId) {
        try {
            List<TblPropEntity> list =
                tblPropService.getTblPropByProjectId(projectId);
            if (CollectionUtils.isEmpty(list)) {
                return Collections.emptyMap();
            }
            Multimap<String, String> multimap = HashMultimap.create();
            for (TblPropEntity domain : list) {
                String tableName = domain.getTableName();
                String prefix = StringUtils.substring(tableName, 0, tableName.indexOf("_"));
                if (StringUtils.isBlank(prefix)) {
                    continue;
                }
                multimap.put(StringUtils.lowerCase(prefix), tableName);
            }
            Map<String, Integer> map = new HashMap<>();
            for (String key : multimap.keySet()) {
                map.put(key, multimap.get(key).size());
            }
            return map;
        } catch (Exception e) {
            log.error("query table count error", e);
        }
        return Collections.emptyMap();
    }
}
